package net.ankao.job.common.route;

import net.ankao.job.entity.AkApplicationClient;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 *
 * 轮询策略
 * @author LILU
 * @date 2024-12-04 9:10
 */
@Component
public class RoundRobinStrategy implements ClientRouteStrategy {

    // 为每个applicationId维护独立的计数器
    private ConcurrentHashMap<String, AtomicInteger> indexMap = new ConcurrentHashMap<>();

    @Override
    public Integer strategyCode() {
        return 2;
    }

    @Override
    public List<AkApplicationClient> route(List<AkApplicationClient> clients) {
        if (clients == null || clients.isEmpty()) {
            return null;
        }

        // 获取applicationId
        String applicationId = clients.get(0).getApplicationId();

        // 获取或创建该应用的计数器
        AtomicInteger index = indexMap.computeIfAbsent(applicationId, k -> new AtomicInteger(0));

        List<AkApplicationClient> availableClients = clients.stream()
                .filter(client -> client.getStatus() == 1)
                .collect(Collectors.toList());

        if (availableClients.isEmpty()) {
            return null;
        }

        int current = index.getAndIncrement() % availableClients.size();
        return Arrays.asList(availableClients.get(current));
    }
}
